//
//  DraggableFloatingButton.swift
//  DKE-Album
//
//  Created by dagny on 2025/11/13.
//  Copyright © 2025 杨东宝. All rights reserved.
//

import UIKit
//委托协议
protocol DraggableFloatingButtonDelegate: AnyObject {
    //刷新
    func addServiceClick();
    
}
class DraggableFloatingButton: UIButton {
    
    // MARK: - Properties
    var delegate:DraggableFloatingButtonDelegate?
    private var panGesture: UIPanGestureRecognizer!
    private var initialCenter: CGPoint = .zero
    internal override var safeAreaInsets: UIEdgeInsets {
        return UIApplication.shared.windows.first?.safeAreaInsets ?? UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    }
    
    // MARK: - Initialization
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupButton()
        setupGestures()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupButton()
        setupGestures()
    }
    
    // MARK: - Setup
    private func setupButton() {
        backgroundColor = .white
        setImage(UIImage(named: "weibiaoti"), for: .normal)
        tintColor = .white
        layer.cornerRadius = 30
        layer.shadowColor = UIColor.black.cgColor
        layer.shadowOffset = CGSize(width: 0, height: 5)
        layer.shadowRadius = 10
        layer.shadowOpacity = 0.3
        
        // 初始位置在右下角
        if let superview = superview {
            frame = CGRect(x: superview.bounds.width - 80,
                          y: superview.bounds.height - 80,
                          width: 60, height: 60)
        }
    }
    private func setupGestures() {
        // 拖动手势
        panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:)))
        addGestureRecognizer(panGesture)
        
        // 点击手势（保持原有的点击功能）
        addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
    }
    
    // MARK: - Gesture Handlers
    @objc private func handlePan(_ gesture: UIPanGestureRecognizer) {
        guard let superview = superview else { return }
        
        let translation = gesture.translation(in: superview)
        
        switch gesture.state {
        case .began:
            initialCenter = center
            // 拖动时的高亮效果
            UIView.animate(withDuration: 0.2) {
                self.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
                self.backgroundColor = self.backgroundColor?.withAlphaComponent(0.8)
            }
            
        case .changed:
            let newCenter = CGPoint(x: initialCenter.x + translation.x,
                                  y: initialCenter.y + translation.y)
            center = newCenter
            
        case .ended, .cancelled:
            // 恢复原始外观
            UIView.animate(withDuration: 0.2) {
                self.transform = .identity
                self.backgroundColor = self.backgroundColor?.withAlphaComponent(1.0)
            }
            
            // 吸附到最近的边缘
            snapToEdge()
            
        default:
            break
        }
    }
    
    @objc private func buttonTapped() {
        print("悬浮按钮被点击")
        self.delegate?.addServiceClick()
        // 添加点击动画
        UIView.animate(withDuration: 0.1, animations: {
            self.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
        }) { _ in
            UIView.animate(withDuration: 0.1) {
                self.transform = .identity
            }
        }
    }
    
    // MARK: - Edge Snapping
    private func snapToEdge() {
        guard let superview = superview else { return }
        
        let centerX = center.x
        let centerY = center.y
        let superviewWidth = superview.bounds.width
        let superviewHeight = superview.bounds.height
        
        // 判断离哪边更近
        let isCloserToLeft = centerX < superviewWidth / 2
        let isCloserToTop = centerY < superviewHeight / 2
        
        // 目标位置（考虑安全区域）
        let targetX: CGFloat
        let targetY: CGFloat
        
        if isCloserToLeft {
            targetX = bounds.width / 2 + safeAreaInsets.left + 20
        } else {
            targetX = superviewWidth - bounds.width / 2 - safeAreaInsets.right - 20
        }
        
        if isCloserToTop {
            targetY = bounds.height / 2 + safeAreaInsets.top + 20
        } else {
            targetY = superviewHeight - bounds.height / 2 - safeAreaInsets.bottom - 20
        }
        
        // 动画移动到目标位置
        UIView.animate(withDuration: 0.3,
                      delay: 0,
                      usingSpringWithDamping: 0.7,
                      initialSpringVelocity: 0.5,
                      options: .curveEaseOut,
                      animations: {
            self.center = CGPoint(x: targetX, y: targetY)
        })
    }
    
    // MARK: - Lifecycle
    override func didMoveToSuperview() {
        super.didMoveToSuperview()
        // 确保按钮在视图层次的最前面
        superview?.bringSubviewToFront(self)
    }
}
